using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Web.SessionState;
using NetWing.Model;
using NetWing.Bll;
using Omu.ValueInjecter;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;
using System.Web.UI;
using static NetWing.BPM.Admin.JydModleOrder.ashx.ajax_submit;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using NetWing.Common.Data.Filter;

namespace NetWing.BPM.Admin.JydDo.ashx
{
    /// <summary>
    /// 时间流程 的摘要说明
    /// </summary>
    public class JydDoHandler : IHttpHandler,IRequiresSessionState
    {
        protected int myyh;
        protected string stmyyhma;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int k;
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<JydDoModel>(context) { CurrentContext = context };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<JydDoModel>>(json);
                rpm.CurrentContext = context;
            }
            else
            {
                rpm.Action = context.Request["action"];
            }

            switch (rpm.Action)
            {
                //执行一个添加
                case "add":
                    string s = context.Request["s"];//格式工艺类型:mainkeyid:orderid:detailkeyid:myorder
                    string[] sarr = s.Split(':');//用冒号拆分数组

                    JydDoModel a = new JydDoModel();
                    a.gytype = sarr[0];//工艺类型
                    a.mainKeyid = int.Parse(sarr[1]);//主订单ID
                    a.detailKeyid = int.Parse(sarr[3]);//子订单ID
                    a.orderid = sarr[2];//订单id
                    a.myorder = sarr[4];//订单名称
                    //通过openID查找用户名
                    string yhmOPID = CookieHelper.GetCookie("OpenID");//用户名
                    
                    if (!string.IsNullOrEmpty(CookieHelper.GetCookie("currentUserName")))
                    {
                        string ccc = SysVisitor.Instance.cookiesUserId;
                        a.domanid = int.Parse(ccc);
                        a.doman = SysVisitor.Instance.cookiesUserName;
                    }
                    else 
                    {

                        string yh = "select * from Sys_Users where OpenID='" + yhmOPID + "' ";
                        DataTable dr = SqlEasy.ExecuteDataTable(yh);

                        foreach (DataRow ztt in dr.Rows)
                        {

                            if (dr.Rows.Count > 0)
                            {
                                myyh = int.Parse(dr.Rows[0]["keyid"].ToString());
                                stmyyhma = dr.Rows[0]["TrueName"].ToString();

                            }
                        }
                       
                        a.domanid = myyh;
                        a.doman = stmyyhma;
                    }
                    
                    a.finishTime = DateTime.Now;
                    a.note = "";    
                    context.Response.Write(JydDoBll.Instance.Add(a));
                    //添加完再催下一组
                    //思路:1.先得到工艺类型对应的角色组
                    //     2.判断角色组排序+1是否存在,如果存在,说明应该催下一道工艺
                    //     3.催促范围当前工艺角色组+1
                    //得到工艺权限组datarow 前提是所有工艺都有对应角色组,排序也是唯一,所以这里不做是否存在的判断
                    DataRow gydr = SqlEasy.ExecuteDataRow("select * from Sys_Roles where remark='"+a.gytype+"'");
                    //得到当前应该催的角色组
                    DataRow nowgydr= SqlEasy.ExecuteDataRow("select * from Sys_Roles where Sortnum="+(int.Parse(gydr["sortnum"].ToString())+1)+"");
                    if (nowgydr!=null)//假如等于null说明工艺角色组不存在,不用催了
                    {
                        //算出当前角色组包含的用户ID
                        DataTable jsidsdt = SqlEasy.ExecuteDataTable("select * from Sys_UserRoles where RoleID="+nowgydr["keyid"].ToString()+"");
                        foreach  (DataRow iddr in jsidsdt.Rows)//得到N多用户ids
                        {
                            //得到用户详细信息 openid不为null 或者不等于空
                            DataRow udr = SqlEasy.ExecuteDataRow("select * from Sys_Users where keyid="+iddr["userid"].ToString()+" and (openid is not null and openid<>'')");
                            if (udr!=null)//如果用户信息存在,则发送催促信息
                            {
                                //得到主订单信息

                                DataRow mainOrderRow = SqlEasy.ExecuteDataRow("select * from jydOrder where keyid="+a.mainKeyid+"");

                                //为模版中的各属性赋值
                                var templateDatac = new ProductTemplateData()
                                {
                                    first = new TemplateDataItem(udr["truename"].ToString() + "您好!"+a.doman+"已完成"+ gydr["RoleName"].ToString() + "工作！您现在急需完成"+ nowgydr["RoleName"].ToString() + "工作↖(^ω^)↗", "#ff0000"),
                                    keyword1 = new TemplateDataItem("订单号:"+a.orderid+","+mainOrderRow["allyspmc"].ToString()+"", "#000000"),//还差所有印刷品名称
                                    keyword2 = new TemplateDataItem("正在走流程", "#000000"),
                                    keyword3 = new TemplateDataItem(DateTime.Now.ToString(), "#000000"),
                                    remark = new TemplateDataItem("本单交货时间:"+mainOrderRow["deliveryDate"].ToString()+",请尽快完成!", "#000000")
                                };
                                string templateidc = NetWing.Common.ConfigHelper.GetValue("templageid1");//从web.config 获得模板ID
                                string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(udr["openid"].ToString(), templateidc, NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/QRCodeView.aspx?keyid=" + a.mainKeyid + "", templateDatac);

                            }

                        }


                    }



                    break;
                case "edit":
                    JydDoModel d = new JydDoModel();
                    d.InjectFrom(rpm.Entity);
                    d.KeyId = rpm.KeyId;
                    context.Response.Write(JydDoBll.Instance.Update(d));
                    break;
                case "export":
                    //string fields = rpm.fields;
                    string fields = rpm.CurrentContext.Request["fields"];
                    string tablename = TableConvention.Resolve(typeof(JydDoModel));//得到表名
                    DataTable xlsDt = SqlEasy.ExecuteDataTable("select " + fields + " from " + tablename + "");
                    ExcelHelper.NPIOtoExcel(xlsDt, HttpContext.Current.Server.MapPath("\\upload\\excel\\" + tablename + ".xls"));
                    context.Response.Write("{\"status\":\"ok\",\"filename\":\"" + tablename + ".xls\"}");
                    break;
                case "inport"://从Excel导入到数据库
                    if (context.Request["REQUEST_METHOD"] == "OPTIONS")
                    {
                        context.Response.End();
                    }
                    SaveFile("~/temp/", context);
                    break;
                case "delete":
                    context.Response.Write(JydDoBll.Instance.Delete(rpm.KeyId));
                    break;
                case "alldel"://2017-04-05新增的功能 批量删除删除结果返回删除条数
                    context.Response.Write(NetWing.Dal.JydDoDal.Instance.Delete(rpm.KeyIds));
                    break;
                case "cbrz"://催别人做
                    try { 
                    string str = context.Request["s"];//格式工艺类型:mainkeyid:orderid:detailkeyid
                    string[] sarrlist = str.Split(':');//用冒号拆分数组
                    string opyh = CookieHelper.GetCookie("openid");
                    DataRow df = SqlEasy.ExecuteDataRow("select KeyId,TrueName,OpenID from Sys_Users where openid='" + opyh + "'");

                    JydOrderModel y = new JydOrderModel();
                    y.OrderID = sarrlist[2];
                    JydDoModel i = new JydDoModel();
                        i.gytype = sarrlist[0];
                    string ddh = y.OrderID;
                    DataRow dtr = SqlEasy.ExecuteDataRow("select * from jydOrder where orderid='" + ddh +"'");




                    //为得到角色的ID
                    DataRow jsdyz = SqlEasy.ExecuteDataRow("select * from Sys_Roles where Remark='" + i.gytype + "'");
                    //这个就是你不动脑子犯下的错误,以后不要这样了
                    //DataRow dyzpx = SqlEasy.ExecuteDataRow("select * from Sys_Roles where Sortnum=" + (int.Parse(jsdyz["Sortnum"].ToString())+1) + "");

                    if(jsdyz != null)
                    {
                        //根据当前角色ID得到用户列表
                        DataTable myyhid = SqlEasy.ExecuteDataTable("select * from Sys_UserRoles where RoleID=" + jsdyz["keyid"].ToString() + "");
                        foreach(DataRow myyhxx in myyhid.Rows)
                        {
                            DataRow myopid = SqlEasy.ExecuteDataRow("select * from Sys_Users where keyid=" + myyhxx["userid"].ToString() + " and (openid is not null and openid<>'')");
                            if(myopid != null)
                            {
                                //为模版中的各属性赋值
                                var templateData = new ProductTemplateData()
                                {
                                    first = new TemplateDataItem(myopid["truename"].ToString() + "您好!请尽快完成" + jsdyz["RoleName"].ToString() + "工作！", "#ff0000"),
                                    keyword1 = new TemplateDataItem("订单号:" + ddh + "," + dtr["allyspmc"].ToString() + "", "#000000"),//还差所有印刷品名称
                                    keyword2 = new TemplateDataItem("正在走流程", "#000000"),
                                    keyword3 = new TemplateDataItem(DateTime.Now.ToString(), "#000000"),
                                    remark = new TemplateDataItem("本单交货时间:" + dtr["deliveryDate"].ToString() + ",请尽快完成!", "#000000")
                                };

                                string templateid = NetWing.Common.ConfigHelper.GetValue("templageid1");//从web.config 获得模板ID
                                                                                                        //通知所有员工就是openid不同
                                
                                string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(myopid["openid"].ToString(), templateid, NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/QRCodeView.aspx?keyid=" + dtr["keyid"].ToString() + "", templateData);
                               if(r != null)
                                    {
                                        context.Response.Write("{\"status\":1,\"msg\":\"通知成功!\"}");
                                    }
                            }


                        }




                    }
                    } catch (Exception e)
                    {
                        WriteLogs.WriteLogsE("Logs", "ccerr >> caozuo", e.Message + " >>> " + e.StackTrace);
                    }




                    break;
                default:
                    //context.Response.Write(JydDoBll.Instance.GetJson(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    //string sqlwhere = "(deptid in (" + SysVisitor.Instance.cookiesUserDepId + "))";
                    //if (SysVisitor.Instance.cookiesIsAdmin == "True")
                    //{ 判断是否是超管如果是超管理，所有显示
                        string sqlwhere = " 1=1 ";//如果是超管则不显示
                    //}
                    if (!string.IsNullOrEmpty(rpm.Filter))//如果筛选不为空
                    {
                        string sstr = " and " + FilterTranslator.ToSql(rpm.Filter);
                        sqlwhere = sqlwhere + sstr;
                    }

                    string sort = rpm.Sort;
                    if (sort == null)
                    {
                        sort = "keyid desc";
                    }
                    //TableConvention.Resolve(typeof(MJUserModel)) 转换成表名
                    var pcpstr = new ProcCustomPage(TableConvention.Resolve(typeof(JydDoModel)))
                    {
                        PageIndex = rpm.Pageindex,
                        PageSize = rpm.Pagesize,
                        //OrderFields = rpm.Sort,
                        OrderFields = sort,
                        WhereString = sqlwhere
                    };
                    int recordCount;
                    DataTable defdt = DbUtils.GetPageWithSp(pcpstr, out recordCount);
                    context.Response.Write(JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, defdt));


                    break;
            }
        }

        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(string basePath, HttpContext context)
        {
            var name = string.Empty;
            basePath = (basePath.IndexOf("~") > -1) ? context.Server.MapPath(basePath) :
            basePath;
            HttpFileCollection files = context.Request.Files;

            if (!Directory.Exists(basePath))//如果文件夹不存在创建文件夹
                Directory.CreateDirectory(basePath);
            //清空temp文件夹
            DirFileHelper.ClearDirectory(basePath);

            var suffix = files[0].ContentType.Split('/');
            var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];

            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }

            var full = basePath + name;
            files[0].SaveAs(full);

            DataTable dt = NPOIHelper.ImportExceltoDt(full);
            string connectionString = SqlEasy.connString;
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = TableConvention.Resolve(typeof(JydDoModel));//数据库中的表名
                                                                                   //自定义的datatable和数据库的字段进行对应  
                                                                                   //sqlBC.ColumnMappings.Add("id", "tel");  
                                                                                   //sqlBC.ColumnMappings.Add("name", "neirong");  
            int k = dt.Rows.Count - 1;                                                                       //注意一个问题，最后一列是字段数
            for (int i = 0; i < (dt.Columns.Count - 1); i++)
            {
                sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName.ToString(), dt.Columns[i].ColumnName.ToString());

            }
            var _result = "";
            try
            {
                sqlbulkcopy.WriteToServer(dt);
                _result = "{\"msg\" : \"导入数据库成功!\", \"result\" : " + k + ", \"filename\" : \"" + name + "\"}";
            }
            catch (Exception)
            {
                _result = "{\"msg\" : \"导入失败,可能模板不对，或其他原因，建议导出数据作为模板重新处理。注意导入没有校验数据重复功能。请人工校验数据!\", \"result\" : 0, \"filename\" : \"" + name + "\"}";
                //throw;
            }



            System.Web.HttpContext.Current.Response.Write(_result);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}